import { menuApi } from "@/api";

interface AddMenu {
  type: "add";
  parentMenu?: Menu;
  subLoading?: boolean;
}
interface EditMenu {
  type: "edit";
  data: Menu;
}
export type Props = AddMenu | EditMenu;
export interface Emits {
  (e: "submitSuccess"): void;
  (e: "submitError"): void;
  (e: "update:subLoading", v: boolean): void;
}

interface Params<T extends Props> {
  type: 0 | 1 | 2;
  props: T;
  emits: Function;
  restoreValid: Function;
}
const useAddMenu = ({
  type,
  props,
  emits,
  restoreValid,
}: Params<AddMenu>) => {
  const initData = (): Menu => ({
    parentId: props.parentMenu?.id,
    type: type,
    name: "",
    order: 0,
    icon: null,
    routeName: null,
    routePath: null,
    component: null,
    newTab: false,
    perms: null,
    status: true,
  });

  const formData = ref<Menu>(initData());

  const handleSubmit = async () => {
    const { status } = await menuApi.add(formData.value);
    if (!status) return;
    window.$message.success("添加成功");
    handleReset();
    emits("submitSuccess");
  };

  const handleReset = () => {
    restoreValid();
    formData.value = initData();
  };

  return {
    formData,
    handleSubmit,
    handleReset,
  };
};

const useEditMenu = ({
  props,
  emits,
  restoreValid,
}: Params<EditMenu>) => {
  const formData = ref<Menu>({ ...props.data! });

  watch(
    () => props.data,
    (newV) => {
      if (newV) formData.value = newV;
    }
  );

  const handleSubmit = async () => {
    const { status } = await menuApi.update(formData.value);
    if (!status) return;
    window.$message.success("修改成功");
    emits("submitSuccess");
  };

  const handleReset = () => {
    restoreValid();
    formData.value = { ...props.data! };
  };

  return {
    formData,
    handleSubmit,
    handleReset,
  };
};

export const useForm = (params: Params<Props>) => {
  if (params.props.type === "add") {
    return useAddMenu(params as Params<AddMenu>);
  } else {
    return useEditMenu(params as Params<EditMenu>);
  }
};
